// pages/app/user/login/login.js
const app = getApp();
var host = app.globalData.host;
var utils = app.globalData.utils;
var cryptoJS = app.globalData.cryptoJS;
var self = null;

Page({
  data: {
    themeColor: '',
    themeColor2: '',
    themeColor3: '',
    defaultColor: '',
    borderColor: '',
    account: '',
    password: '',
    valiCode: '',
    isRegistered: true,
    countDown: 0,
    intervalId: null
  },
  watch: {
    countDown: function (val) {
      if (self.data.countDown <= 0) {
        clearInterval(self.data.intervalId);
      }
    }
  },
  onLoad: function (options) {
    app.setWatcher(this.data, this.watch); // 设置监听器
    self = this;
    self.getStyle();
    // app.loginWechat();
  },
  onShow: function () {
    // wx.getSetting({
    //   success: res => {
    //     if (res.authSetting['scope.userInfo']) {
    //       self.setData({
    //         isWechatAuthed: true
    //       })
    //     }
    //   }
    // })
  },
  getStyle() {
    self.setData({
      themeColor: app.globalData.themeColor,
      themeColor2: app.globalData.themeColor2,
      themeColor3: app.globalData.themeColor3,
      defaultColor: app.globalData.defaultColor,
      borderColor: app.globalData.borderColor
    })
  },
  onAccountChange(event) {
    this.setData({
      account: event.detail.value
    })
  },
  onPasswordChange(event) {
    this.setData({
      password: event.detail.value
    })
  },
  onValiCodeChange(event) {
    this.setData({
      valiCode: event.detail.value
    })
  },
  loginWithCode(event) {
    wx.navigateTo({
      url: '/pages/app/user/loginWithCode/loginWithCode'
    })
  },
  forgetPwd(event) {
    wx.navigateTo({
      url: '/pages/app/user/forgetPwd/forgetPwd'
    })
  },
  signUp(event) {
    wx.navigateTo({
      // url: '/pages/app/user/valiMobile/valiMobile'
      url: '/pages/app/user/signUp/signUp'
    })
  },
  sendCode(e) {
    if (self.data.countDown) {
      return;
    }
    if (!self.data.account) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return;
    }
    if (!/^[1][0-9]{10}$/.test(self.data.account)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return;
    }
    var url = host + '/lx/mini/user/sendCode';
    var params = {
      mobile: self.data.account
    };
    var success = function (res) {
      wx.showToast({
        title: '验证码发送成功',
        icon: 'none'
      })
      self.setData({
        countDown: 60
      })
      var intervalId = setInterval(function () {
        self.setData({
          countDown: self.data.countDown - 1
        })
      }, 1000);
      self.setData({
        intervalId: intervalId
      })
    }
    var fail = function () { };
    var complete = function () { };
    utils.request(url, params, success, fail, complete);
  },
  login(event) {
    // var url = host + '/lx/mini/user/login';
    // var key = cryptoJS.enc.Utf8.parse(app.globalData.aesKey);
    // var iv = cryptoJS.enc.Utf8.parse('RandomInitVector');
    // var aesText = cryptoJS.AES.encrypt(self.data.password, key, {
    //   iv: iv,
    //   mode: cryptoJS.mode.CBC,
    //   padding: cryptoJS.pad.Pkcs7
    // }).toString();
    // var params = {
    //   account: self.data.account,
    //   password: aesText
    // };
    // var success = function (res) {
    //   app.globalData.userInfo = res.info;
    //   wx.setStorageSync("openId", res.info.openId);
    //   wx.setStorageSync("user", res.info);
    //   if (wx.getStorageSync("path")) {
    //     wx.reLaunch({
    //       url: "/" + wx.getStorageSync("path")
    //     })
    //     wx.setStorageSync("path", null);
    //   } else {
    //     wx.reLaunch({
    //       url: '/pages/app/schools/index/index'
    //     })
    //   }
    // }
    // var fail = function () { };
    // var complete = function () { };
    // utils.request(url, params, success, fail, complete);

    var url = host + '/lx/mini/user/bind';
    var params = {
      account: self.data.account,
      // password: self.data.password,
      code: self.data.valiCode,
      openId: app.globalData.openId
    };
    if (app.globalData.unionId) {
      params.unionId = app.globalData.unionId
    }
    var success = function (res) {
      console.log(res);
      if (res.status == 200 && res.info.isRegistered == 1) {
        app.globalData.userInfo = res.info.user;
        app.globalData.openId = res.info.openId;
        wx.setStorageSync("openId", res.info.openId);
        wx.setStorageSync("token", res.info.token);
        wx.setStorageSync("user", res.info.user);
        if (wx.getStorageSync("path")) {
          wx.reLaunch({
            url: "/" + wx.getStorageSync("path")
          })
          wx.setStorageSync("path", null);
        } else {
          wx.reLaunch({
            url: '/pages/app/schools/index/index'
          })
        }

      } else if (res.status == 200 && res.info.isRegistered == 0) {
        wx.navigateTo({
          url: '/pages/app/user/signUp/signUp?account=' + res.info.account
        })
      }
    }
    var fail = function () { };
    var complete = function () { };
    utils.request(url, params, success, fail, complete);
  },
  getUserInfo(e) {
    console.log(e);
    wx.login({
      success: function (res) {
        var code = res.code
        wx.getUserInfo({
          success: function (res) {
            var userInfo = res.userInfo
            var nickName = userInfo.nickName
            var avatarUrl = userInfo.avatarUrl
            var gender = userInfo.gender //性别 0：未知、1：男、2：女
            var province = userInfo.province
            var city = userInfo.city
            var country = userInfo.country


            var host = app.globalData.host
            app.request({
              url: host + '/lx/mini/user/auth',
              data: {
                code: code,
                nickName: nickName,
                avatarUrl: avatarUrl,
                gender: gender,
                province: province,
                country: country
              },
              success: function (res) {
                console.log(res);
                if (res.data.status == 200) {
                  var openId = res.data.info.openId
                  var unionId = res.data.info.unionId
                  var token = res.data.info.token
                  var userInfo = res.data.info.user
                  app.globalData.openId = openId
                  app.globalData.unionId = unionId
                  app.globalData.token = token
                  app.globalData.userInfo = userInfo
                  wx.setStorage({
                    key: "openId",
                    data: openId
                  })
                  wx.setStorage({
                    key: "token",
                    data: token
                  })
                  wx.setStorage({
                    key: "user",
                    data: userInfo
                  })
                  if (wx.getStorageSync("path")) {
                    wx.reLaunch({
                      url: "/" + wx.getStorageSync("path")
                    })
                    wx.setStorageSync("path", null);
                  } else {
                    wx.reLaunch({
                      url: '/pages/app/schools/index/index'
                    })
                  }
                  
                } else if (res.data.status == 206) {
                  var openId = res.data.info.openId
                  var unionId = res.data.info.unionId
                  app.globalData.openId = openId
                  app.globalData.unionId = unionId
                  wx.setStorage({
                    key: "openId",
                    data: openId
                  })
                  self.setData({
                    isRegistered: false
                  })

                } else {
                  console.log(res);
                }
              }
            })
          }
        })
      },
      fail(errMsg) {
        console.log(errMsg)
      }
    })
    // wx.login({
    //   success: res => {
    //     var code = res.code;
    //     wx.request({
    //       url: host + '/lx/mini/user/wechatLogin',
    //       data: {
    //         code: code
    //       },
    //       success: res => {
    //         console.log(res);
    //         if (res.data.info.isRegistered == 1 ) {
    //           wx.setStorageSync("user", res.data.info.user)
    //           wx.setStorageSync("openId", res.data.info.user.openId);
    //           if (wx.getStorageSync("path")) {
    //             wx.reLaunch({
    //               url: "/" + wx.getStorageSync("path")
    //             })
    //             wx.setStorageSync("path", null);
    //           } else {
    //             wx.reLaunch({
    //               url: '/pages/app/schools/index/index'
    //             })
    //           }

    //         } else {
    //           self.setData({
    //             isRegistered: false
    //           })
    //         }
    //       }
    //     })
    //   }
    // })
  },
  getPhoneNumber(e) {
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      wx.checkSession({
        success() {
          var nickName = '';
          var avatarUrl = '';
          var gender = '';
          var province = '';
          var city = '';
          var country = '';
          wx.getUserInfo({
            success: res => {
              console.log(res);
              var userInfo = res.userInfo
              nickName = userInfo.nickName
              avatarUrl = userInfo.avatarUrl
              gender = userInfo.gender //性别 0：未知、1：男、2：女
              province = userInfo.province
              city = userInfo.city
              country = userInfo.country

              var url = host + '/lx/mini/user/checkPhoneNumber';
              var params = {
                encryptedData: e.detail.encryptedData,
                iv: e.detail.iv,
                nickName: nickName,
                avatarUrl: avatarUrl,
                gender: gender,
                province: province,
                city: city,
                country: country
              };
              var success = function (res) {
                console.log(res);
                if (res.info.isRegistered == 1) {
                  app.globalData.userInfo = res.info.user;
                  wx.setStorageSync("openId", res.info.user.openId);
                  wx.setStorageSync("user", res.info.user);
                  if (wx.getStorageSync("path")) {
                    wx.reLaunch({
                      url: "/" + wx.getStorageSync("path")
                    })
                    wx.setStorageSync("path", null);
                  } else {
                    wx.reLaunch({
                      url: '/pages/app/schools/index/index'
                    })
                  }
                } else {
                  wx.navigateTo({
                    url: '/pages/app/user/signUp/signUp?id=' + res.info.id + '&account=' + res.info.account
                  })
                }
              }
              var fail = function (res) {
              };
              var complete = function () { };
              utils.request(url, params, success, fail, complete);
            },
            fail(errMsg) {
              console.log(errMsg);
              wx.showToast({
                title: '获取微信用户信息失败',
                icon: 'none'
              })
            }
          })
        },
        fail() {
          // app.loginWechat(this.getPhoneNumber);
        }
      })
      
    } else {
      wx.showToast({
        title: '获取手机号失败',
        icon: 'none'
      })
    }
  },
  goHome(e) {
    wx.switchTab({
      url: '/pages/app/schools/index/index'
    })
  },
  goCert(e) {
    wx.switchTab({
      url: '/pages/app/certification/index/index'
    })
  },
  goSearch(e) {
    wx.switchTab({
      url: '/pages/index/index'
    })
  }
})